<?php
require_once('include/config.php');
require_once '../include/config.php';
$msg = $msgNom = $nom = $date = $adr = $adr2 = $cp = $ville = $paiement = $produit = '';

function addProduit($idClient, $tabDesignation, $tabQte, $tabPu, $tabTva) {
    $compteur = 0;
    $total = 0;
    foreach ($tabDesignation as $value) {
        if (trim($value) != '') {
            //Ensuite on insert l'ensemble des lignes de son devis/facture
            $sql = 'INSERT INTO `fact-designation` (`fact_id_desg`,`fact_id`, `fact_desgn`, `fact_qte`, `fact_pu`, `fact_tva`)
                    VALUES (NULL, ' . $idClient . ',
                    "' . mysql_real_escape_string($value) . '",
                    "' . mysql_real_escape_string($tabQte[$compteur]) . '",
                    "' . mysql_real_escape_string(floatPoint($tabPu[$compteur])) . '",
                    "' . mysql_real_escape_string(floatPoint($tabTva[$compteur])) . '")';
            $res = @mysql_query($sql) or die(mysql_error());
            //On en profit pour calculer le total
            $total += $tabQte[$compteur] * floatPoint($tabPu[$compteur++]);
        }
    }

    //Puis on met à jour le Total TTC
    $sql = 'UPDATE `fact-client` SET `fact_total`=\'' . mysql_real_escape_string($total) . '\' WHERE `fact_id`=\'' . $idClient . '\'';
    $res = @mysql_query($sql) or die(mysql_error());
    return $res;
}

//Si on arrive sur cette page pour modifier
if (isset($_GET['id'])) {
    $id = htmlentities($_GET['id'], ENT_QUOTES);

    $sql = 'SELECT * FROM `fact-client` WHERE `fact_id`=' . $id;
    $result = @mysql_query($sql);
    $nbr_actu = @mysql_num_rows($result);
    if ($nbr_actu > 0) {
        $data = @mysql_fetch_array($result);
        $nom = $data['fact_nom'];
        $adr = $data['fact_adr'];
        $adr2 = $data['fact_adr2'];
        $cp = $data['fact_cp'];
        $ville = $data['fact_ville'];
        $paiement = $data['fact_paiement'];
    }

    //on récupère tous les produits de ce client
    $sql = 'SELECT * FROM `fact-designation` WHERE `fact_id`=' . $id;
    $result = @mysql_query($sql);
    $nbr_produit = @mysql_num_rows($result);
    if ($nbr_produit > 0) {
        while ($data = @mysql_fetch_array($result)) {
            $designation[] = $data['fact_desgn'];
            $qte[] = $data['fact_qte'];
            $pu[] = $data['fact_pu'];
            $tva[] = $data['fact_tva'];
        }
    }
}


//Dans le cas ou l'on vient sur cette page en envoyant le formulaire
if (!empty($_POST['Envoyer'])) {
    //on récupère les variables
    $nom = $_POST['nom'];
    $adr = $_POST['adr'];
    $adr2 = $_POST['adr2'];
    $cp = $_POST['cp'];
    $ville = $_POST['ville'];
    $paiement = $_POST['paiement'];

    //récupération des données du devis/facture
    $designation = $_POST['designation'];
    $qte = $_POST['qte'];
    $pu = $_POST['pu'];
    $tva = $_POST['tva'];

    //on vérifie que les champs obligatoires sont présent
    if ((!empty($nom)) && (intval($paiement) >= 0) && (count($designation) > 0)) {
        //Gestion de l'intertion ou la modification
        if (!isset($id)) {
            //On commence par insérer le client
            $sql = 'INSERT INTO `fact-client` (`fact_id`, `fact_date`, `fact_nom`, `fact_adr`, `fact_adr2`, `fact_cp`, `fact_ville`, `fact_paiement`) 
                VALUES (NULL, NOW(),
                "' . mysql_real_escape_string($nom) . '",                
                "' . mysql_real_escape_string($adr) . '",
                "' . mysql_real_escape_string($adr2) . '",
                "' . mysql_real_escape_string($cp) . '",
                "' . mysql_real_escape_string($ville) . '",
                "' . mysql_real_escape_string($paiement) . '")';
            @mysql_query("SET NAMES 'utf8'");
            $res = @mysql_query($sql) or die(mysql_error());
            $lastID = @mysql_insert_id();

            //puis on ajoute les nouvelles entrée            
            if (addProduit($lastID, $designation, $qte, $pu, $tva)) {
                $msg = '<p class="msg done">Le document a bien été modifié</p>';
                $nom = $date = $adr = $adr2 = $cp = $ville = '';
                $nbr_produit = 0;
            }
        } else {
            //dans le cas d'une modification
            //On commence par mettre à jour les informations du client
            $sql = 'UPDATE `fact-client` SET 
                `fact_nom`=\'' . mysql_real_escape_string($nom) . '\',
                 `fact_date`=NOW(),
                 `fact_adr`=\'' . mysql_real_escape_string($adr) . '\',
                 `fact_adr2`=\'' . mysql_real_escape_string($adr2) . '\',
                 `fact_cp`=\'' . mysql_real_escape_string($cp) . '\',
                 `fact_ville`=\'' . mysql_real_escape_string($ville) . '\',
                 `fact_paiement`=\'' . mysql_real_escape_string($paiement) . '\'
                  WHERE `fact_id`=' . $id;
            $res = @mysql_query($sql) or die(mysql_error());

            //Puis on met à jour les produits
            // On supprimer toutes les enciennes entrée puis on remet les nouvelles.
            $sql = 'DELETE FROM `fact-designation` WHERE `fact_id`=' . $id;
            $res = @mysql_query($sql) or die(mysql_error());

            //puis on ajoute les nouvelles entrée            
            if (addProduit($id, $designation, $qte, $pu, $tva)) {
                $msg = '<p class="msg done">Le document a bien été modifié</p>';
                //on récupère tous les produits de ce client
                $sql = 'SELECT * FROM `fact-designation` WHERE `fact_id`=' . $id;
                $result = @mysql_query($sql);
                $nbr_produit = @mysql_num_rows($result);
                if ($nbr_produit > 0) {
                    while ($data = @mysql_fetch_array($result)) {
                        $designation[] = $data['fact_desgn'];
                        $qte[] = $data['fact_qte'];
                        $pu[] = $data['fact_pu'];
                        $tva[] = $data['fact_tva'];
                    }
                }
            }
        }
    } else {
        //gestion des erreurs approfondi
        $msgErr = '<p class="msg warning">Les champs muni d\'une astérisque sont obligatoire</p>';
        if (empty($_POST['nom'])) {
            $msgNom = '<p class="msg error">Merci de renseigner un nom de client</p>';
        }
        if ((count($designation) < 1)) {
            $msgProduit = '<p class="msg error">Merci de renseigner au moins une ligne</p>';
        }
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//FR" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="content-language" content="en" />
        <meta name="robots" content="noindex,nofollow" />
        <link rel="stylesheet" media="screen,projection" type="text/css" href="css/reset.css" /> <!-- RESET -->
        <link rel="stylesheet" media="screen,projection" type="text/css" href="css/main.css" /> <!-- MAIN STYLE SHEET -->
        <link rel="stylesheet" media="screen,projection" type="text/css" href="css/2col.css" title="2col" /> <!-- DEFAULT: 2 COLUMNS -->
        <link rel="alternate stylesheet" media="screen,projection" type="text/css" href="css/1col.css" title="1col" /> <!-- ALTERNATE: 1 COLUMN -->
        <!--[if lte IE 6]><link rel="stylesheet" media="screen,projection" type="text/css" href="css/main-ie6.css" /><![endif]--> <!-- MSIE6 -->
        <link rel="stylesheet" media="screen,projection" type="text/css" href="css/style.css" /> <!-- GRAPHIC THEME -->
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

        <title>Administration</title>
    </head>

    <body>
        <div id="main">
            <!-- Tray -->
            <div id="tray" class="box">
                <p class="f-left box">
                    <!-- Switcher -->
                    <span class="f-left" id="switcher">
                        <a href="#" rel="1col" class="styleswitch ico-col1" title="Enlever le menu gauche"><img src="design/switcher-1col.gif" alt="1 Column" /></a>
                        <a href="#" rel="2col" class="styleswitch ico-col2" title="Menu gauche"><img src="design/switcher-2col.gif" alt="2 Columns" /></a>
                    </span>
                    <strong><?php echo $nomProjet; ?></strong>
                </p>
                <p class="f-right"><a href="<?php echo $site; ?>" target="_blank" id="logout"><span><strong>Voir le site</strong></span></a>&nbsp;&nbsp;&nbsp;&nbsp;<strong><a href="logout.php" id="logout">Quitter l'administration</a></strong></p>
            </div> <!--  /tray -->
            <hr class="noscreen" />

            <!-- Columns -->
            <div id="cols" class="box">

                <!-- Aside (Left Column) -->
                <div id="aside" class="box">
<?php
require_once('include/menu-gauche.php');
?>
                </div> <!-- /aside -->

                <hr class="noscreen" />

                <!-- Content (Right Column) -->
                <div id="content" class="box">
<?php
if (!isset($id)) {
    echo '<h1>Ajouter une Facture/Devis</h1>';
} else {
    echo '<h1>Modifier un Facture/Devis</h1>';
}
if ($msg != '')
    echo $msg;

//gestion de l'url
if (!isset($id)) {
    $urlDestination = htmlentities($_SERVER['PHP_SELF']);
} else {
    $urlDestination = htmlentities($_SERVER['PHP_SELF']) . '?id=' . $id;
}
?>
                    <form action="<?php echo $urlDestination; ?>" method="post" enctype="multipart/form-data">
                        <fieldset>
                            <legend> Client</legend>
                            <table class="nostyle" border="1">
                                <tr>
                                    <td style="width:90px;">Nom * :</td>
                                    <td>
                                        <input type="text" size="40" name="nom" class="input-text" value="<?php echo stripcslashes($nom); ?>" />
<?php
if ($msgNom != '')
    echo $msgNom;
?>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:90px;">Adresse :</td>
                                    <td>
                                        <input type="text" size="40" name="adr" class="input-text" value="<?php echo stripcslashes($adr); ?>" />
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:90px;">Adresse 2 :</td>
                                    <td>
                                        <input type="text" size="40" name="adr2" class="input-text" value="<?php echo stripcslashes($adr2); ?>" />
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:90px;">CP :</td>
                                    <td>
                                        <input type="text" size="40" name="cp" class="input-text" value="<?php echo stripcslashes($cp); ?>" />
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:90px;">Ville :</td>
                                    <td>
                                        <input type="text" size="40" name="ville" class="input-text" value="<?php echo stripcslashes($ville); ?>" />
                                    </td>
                                </tr>
                                <tr>
                                    <td style="width:90px;">Paiement :</td>
                                    <td>
                                        <input type="radio" name="paiement" class="input-radio" value="0" <?php echo check($paiement, 0, ''); ?>/> Devis
                                        <input type="radio" name="paiement" class="input-radio" value="1" <?php echo check($paiement, 1, ''); ?>/> Chèque
                                        <input type="radio" name="paiement" class="input-radio" value="2" <?php echo check($paiement, 2, ''); ?>/> Espèce
                                        <input type="radio" name="paiement" class="input-radio" value="3" <?php echo check($paiement, 3, ''); ?>/> Virement
                                        <input type="radio" name="paiement" class="input-radio" value="4" <?php echo check($paiement, 4, ''); ?>/> CB
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                        <fieldset>
                            <legend> Produit</legend>
                            <table class="nostyle">
                                <tr>
                                    <th style="width:60px;">Désignation</th>
                                    <th style="width:20px;">Qte</th>
                                    <th style="width:40px;">PU TTC</th>
                                    <th style="width:70px;">TVA</th>                                    
                                </tr>
<?php
if ((isset($nbr_produit)) && ($nbr_produit > 0)) {
    for ($i = 0; $i < $nbr_produit; $i++) {
        ?>

                                        <tr class="produit">
                                            <td>
                                                <input type="text" size="50" name="designation[]" class="input-text" value="<?php echo stripcslashes($designation[$i]); ?>" />
                                            </td>
                                            <td>
                                                <input type="text" size="2" name="qte[]" class="input-text" value="<?php echo $qte[$i]; ?>" />
                                            </td>
                                            <td>
                                                <input type="text" size="4" name="pu[]" class="input-text" value="<?php echo $pu[$i]; ?>" />
                                            </td>
                                            <td>
                                                <input type="text" size="4" name="tva[]" class="input-text" value="<?php echo $tva[$i]; ?>" />
                                            </td>                                    
                                        </tr>
        <?php
    }
} else {
    ?>
                                    <tr class="produit">
                                        <td>
                                            <input type="text" size="50" name="designation[]" class="input-text" value="" />
                                        </td>
                                        <td>
                                            <input type="text" size="2" name="qte[]" class="input-text" value="" />
                                        </td>
                                        <td>
                                            <input type="text" size="4" name="pu[]" class="input-text" value="" />
                                        </td>
                                        <td>
                                            <input type="text" size="4" name="tva[]" class="input-text" value="" />
                                        </td>                                    
                                    </tr>
    <?php
}
?>

                            </table>
                            <input id="ajoutArticle" type="button" value="Ajouter un produit"/>
                        </fieldset>
                        <table class="nostyle" border="1">
                            <tr>
                                <td colspan="2" class="t-right"><input type="submit" class="input-submit" name="Envoyer" value="Valider" /></td>
                            </tr>
                        </table>

                    </form>
                </div> <!-- /content -->
            </div> <!-- /cols -->
            <?php
            require_once ('include/footer.php');
            ?>
        </div> <!-- /main -->
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/switcher.js"></script>
        <script type="text/javascript" src="js/toggle.js"></script>
        <script type="text/javascript" src="js/ui.core.js"></script>
        <script type="text/javascript" src="js/ui.tabs.js"></script>
        <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
        <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>


        <script type="text/javascript">

            $(document).ready(function() {
                $(".tabs > ul").tabs();

                $("#ajoutArticle").click(function() {
                    var form = $(this).closest('form');
                    var articleList = form.find('.produit');
                    // Le nombre d'articles déjà présents
                    var n = articleList.length;
                    // Le premier article que l'on va cloner
                    var firstArticle = $(articleList[0]);
                    // Le dernier article de la liste
                    var lastArticle = $(articleList[n - 1]);
                    // Un article cloné
                    var clonedArticle = firstArticle.clone();

                    // Pour chaque input clonés
                    clonedArticle.find(':input').each(function() {
                        // On vide la valeur
                        $(this)
                                .filter(':text').val('').end()
                    })

                    // On l'ajoute au dom après les autres
                    clonedArticle.insertAfter(lastArticle).hide().fadeIn('slow');
                });
            });
        </script>
    </body>
</html>